﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NCRGEA.UtilityForms
{
    public partial class frmLogin : Form
    {
        bool loggedIn = false;
        public frmLogin()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            AAL.User currentUser = AAL.UAL.AuthenticateUser(txtUsername.Text, txtPassword.Text);
            if (currentUser != null)
            {
                Logger.Log("User " + txtUsername.Text + " logged in.");
                loggedIn = true;

                ((frmMain)MdiParent).LogIn(currentUser);  //Log in
                Cursor.Current = Cursors.Default;
                this.Close();
            }
            else
            {
                InvalidLogin();
                Cursor.Current = Cursors.Default;
            }

        }

        private void InvalidLogin()
        {
            Logger.Log("Invalid login for " + txtUsername.Text);
            txtPassword.Text = string.Empty;
            txtUsername.Text = string.Empty;
            txtUsername.Focus();
            MessageBox.Show("Invalid login!", "NCRGEA - Login");
        }

        private void txtPassword_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnLogin_Click(sender, e);
        }

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(!loggedIn)
                Application.Exit();
        }
    }
}
